package com.va1m.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.va1m.demo.entity.Member;
import com.va1m.demo.entity.Record;
import com.va1m.demo.mapper.MemberMapper;
import com.va1m.demo.mapper.RecordMapper;
import com.va1m.demo.service.RecordService;
import com.va1m.demo.vo.RecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 处理消费记录的service
 * @author Admin
 */
@Service
public class RecordServiceImpl implements RecordService {
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    MemberMapper memberMapper;

    @Override
    public List<RecordVo> getRecordList(Integer userId) {
        //条件查询 根据userId查询该用户的消费记录
        List<Record> records = recordMapper.selectList(
                new LambdaQueryWrapper<Record>().eq(Record::getUserId, userId));
        //查询所有会员充值信息
        List<Member> members = memberMapper.selectList(null);
        //根据充值金额进行分桶
        Map<BigDecimal, List<Member>> map =
                members.stream().collect(Collectors.groupingBy(Member::getAmount));
        //遍历分桶后的集合  生成一个 金额-描述 对应的map
        HashMap<BigDecimal, String> kvmap = new HashMap<>();
        map.forEach((k,v) ->{
            kvmap.put(k,v.get(0).getDescription());
        });
        //创建容器接收返回结果
        List<RecordVo> recordVos = new ArrayList<>();
        //数据转换 record -> recordVo
        records.stream().forEach(record -> {
            RecordVo recordVo = new RecordVo();
            //设置金额
            recordVo.setAmount(record.getAmount());
            //设置格式化时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH：mm：ss");
            String format = simpleDateFormat.format(record.getDate());
            recordVo.setFormatDate(format);
            //设置消费描述
            recordVo.setDescription(kvmap.get(record.getAmount()));
            //添加到返回容器中
            recordVos.add(recordVo);
        });

        return recordVos;
    }
}
